package com.lei.springbootpractice.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lei.springbootpractice.dao.ProductsDao;
import com.lei.springbootpractice.pojo.CategoryPojo;
import com.lei.springbootpractice.pojo.ProductsPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProductsService {
    @Autowired
    private ProductsDao productsDao;

    @Autowired
    private CategoryService categoryService;

    // 获取所有商品（包含分类信息）
    public List<ProductsPojo> getAllProducts() {
        List<ProductsPojo> products = productsDao.selectList(null);
        // 批量填充分类信息，避免N+1查询
        fillCategoryInfoBatch(products);
        return products;
    }

    // 根据分类获取商品
    public List<ProductsPojo> getProductsByCategory(String categoryId) {
        QueryWrapper<ProductsPojo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId);
        List<ProductsPojo> products = productsDao.selectList(queryWrapper);
        fillCategoryInfoBatch(products);
        return products;
    }

    // 根据价格范围筛选商品
    public List<ProductsPojo> getProductsByPriceRange(double minPrice, double maxPrice) {
        QueryWrapper<ProductsPojo> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("price", minPrice, maxPrice);
        List<ProductsPojo> products = productsDao.selectList(queryWrapper);
        fillCategoryInfoBatch(products);
        return products;
    }

    // 根据多个条件筛选商品 - 优化版本，直接使用JOIN查询
    public List<ProductsPojo> getProductsByFilter(List<String> categoryIds, Double minPrice, Double maxPrice) {
        return productsDao.selectProductsWithFilter(categoryIds, minPrice, maxPrice);
    }

    // 根据单个分类ID筛选商品
    public List<ProductsPojo> getProductsByFilter(String categoryId, Double minPrice, Double maxPrice) {
        List<String> categoryIds = categoryId != null ? List.of(categoryId) : null;
        return getProductsByFilter(categoryIds, minPrice, maxPrice);
    }

    // 添加新商品
    public boolean addProduct(ProductsPojo product) {
        return productsDao.insert(product) > 0;
    }

    // 根据ID获取商品
    public ProductsPojo getProductById(String productId) {
        ProductsPojo product = productsDao.selectById(productId);
        if (product != null) {
            fillCategoryInfo(product);
        }
        return product;
    }

    // 更新商品信息
    public boolean updateProduct(ProductsPojo product) {
        return productsDao.updateById(product) > 0;
    }

    // 删除商品
    public boolean deleteProduct(String productId) {
        return productsDao.deleteById(productId) > 0;
    }

    // 批量填充分类信息 - 避免N+1查询
    private void fillCategoryInfoBatch(List<ProductsPojo> products) {
        if (products == null || products.isEmpty()) {
            return;
        }

        // 收集所有需要查询的分类ID
        List<String> categoryIds = products.stream()
                .map(ProductsPojo::getCategoryId)
                .distinct()
                .collect(Collectors.toList());

        // 批量获取分类信息
        Map<String, CategoryPojo> categoryMap = categoryService.getCategoriesByIds(categoryIds)
                .stream()
                .collect(Collectors.toMap(CategoryPojo::getCategoryId, category -> category));

        // 收集父分类ID
        List<String> parentCategoryIds = categoryMap.values().stream()
                .map(CategoryPojo::getParentCategoryId)
                .filter(id -> id != null)
                .distinct()
                .collect(Collectors.toList());

        // 批量获取父分类信息
        Map<String, CategoryPojo> parentCategoryMap = Map.of();
        if (!parentCategoryIds.isEmpty()) {
            parentCategoryMap = categoryService.getCategoriesByIds(parentCategoryIds)
                    .stream()
                    .collect(Collectors.toMap(CategoryPojo::getCategoryId, category -> category));
        }

        // 填充商品的分类信息
        for (ProductsPojo product : products) {
            CategoryPojo category = categoryMap.get(product.getCategoryId());
            if (category != null) {
                product.setCategoryName(category.getCategoryName());
                if (category.getParentCategoryId() != null) {
                    CategoryPojo parentCategory = parentCategoryMap.get(category.getParentCategoryId());
                    if (parentCategory != null) {
                        product.setParentCategoryName(parentCategory.getCategoryName());
                    }
                }
            }
        }
    }

    // 填充单个商品的分类信息
    private void fillCategoryInfo(ProductsPojo product) {
        if (product != null && product.getCategoryId() != null) {
            CategoryPojo category = categoryService.getCategoryById(product.getCategoryId());
            if (category != null) {
                product.setCategoryName(category.getCategoryName());
                if (category.getParentCategoryId() != null) {
                    CategoryPojo parentCategory = categoryService.getCategoryById(category.getParentCategoryId());
                    if (parentCategory != null) {
                        product.setParentCategoryName(parentCategory.getCategoryName());
                    }
                }
            }
        }
    }
}
